var http = require('http');
var config = require('./config');
var fs = require('fs');
var path = require('path');
let AdmZip = require('adm-zip-iconv')


main();
function main(){
    var args = process.argv.splice(2);
    if(args==null||args.length==0){
        console.log("请输入下载key");
        return;
    }

   var downloadFile=  function (url,dz){
        http.get(url, (res)=>{
            var fileName=res.headers['content-disposition'];
            fileName=fileName.substring(fileName.indexOf("filename=")+9,fileName.length);
            var folder=fileName.substring(0,fileName.indexOf(".zip"));
            var dest = path.join(dz, fileName);
            var file = fs.createWriteStream(dest);
            if(res.statusCode !== 200){
                console.log("请求出错");
                return;
            }
            res.on('end', ()=>{

            });
            // 进度、超时等
            file.on('finish', ()=>{
                console.log('下载完成');
                let unzip = new AdmZip(dz+fileName, 'UTF-8')
                unzip.extractAllTo(dz, true);
                fs.unlink(dz+fileName,function(){
                    console.log("解压完成");
                });
            }).on('error', (err)=>{
                fs.unlink(dest);
                console.log('下载错误');
            })
            res.pipe(file);
        });
    }
    var dz="./";
    if(args.length>1){
        dz=args[1];
    }
    downloadFile(config.downloadHttp+"codeDownload/download/"+args[0]+"/2",dz);
}

